<?php
namespace app\admin\controller;

use app\admin\model\AdminUser;
use app\admin\model\Captcha;
use app\admin\BaseController;
use think\facade\Cookie;
use think\facade\Session;

class Login extends BaseController
{
    public function index()
    {
        return view('login/index', [
            'title'  => '登录',
            'img' => '/common/captcha'
        ]);
    }

    /**
     * @return \think\response\Redirect
     * @throws \app\admin\CommonException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function loginForm(){
        $data = $this->request->post();
        if(!isset($data['captcha'])) return redirect('index');

        $model = new Captcha();
        $check = $model->checkCaptcha(Captcha::LOGIN_CAPTCHA,$this->request->post('captcha'));
        if(!$check) error('验证码错误!');

        $validate = new \app\validate\AdminUser();
        $result = $validate->check($data);
        if($result) error($validate->getError());

        $remember = isset($data['remember']);
        $model = new AdminUser();
        $model->login($data['username'],$data['password'],$remember);
        return redirect('/index/index');
    }

    /**
     * 推出登陆
     */
    public function loginOut(){
        Session::set(AdminUser::LOGIN_NAME,null);
        Session::delete(AdminUser::LOGIN_NAME);
        if( Cookie::has('username')) {
            Cookie::set('username','');
            Cookie::delete('username');
        }
        if( Cookie::has('password')) {
            Cookie::set('password','');
            Cookie::delete('password');
        }
        return redirect('/login/index');
    }
}
